/*
 * METSCreatorGUIView.java
 */
package metscreatorgui;

import java.io.UnsupportedEncodingException;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import monash.med.crystallography.DatasetTools.MetsCreator.MetsCreator;

import java.io.File;
import java.net.URL;
import java.net.URLDecoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;

/**
 * The application's main frame.
 */
public class METSCreatorGUIView extends FrameView {
    
     public String locate() throws ClassNotFoundException, UnsupportedEncodingException {

        final URL location;
        final String classLocation = this.getClass().getName().replace('.', '/') + ".class";
        final ClassLoader loader = this.getClass().getClassLoader();
        if( loader == null )
        {
          location = ClassLoader.getSystemResource(classLocation);
        }
        else
        {
          location = loader.getResource(classLocation);
        }
        if( location != null ) 
        {
          Pattern p = Pattern.compile( "^.*:(.*)!.*$" ) ;

          Matcher m = p.matcher( URLDecoder.decode(location.getPath(), "UTF-8") );
          if( m.find() )
            return new File(m.group( 1 )).getParent();
          else
            throw new ClassNotFoundException( "Cannot parse location of '" + location + "'.  Probably not loaded from a Jar" ) ;
        }
        else 
          throw new ClassNotFoundException( "Cannot find class '" + this.getClass().getName() + " using the classloader" ) ;
  }      

    public METSCreatorGUIView(SingleFrameApplication app) {
        super(app);

        initComponents();
        
        try{

        
        String resource = locate();
         
        String strOutputPath = resource + File.separator + "Example";  
        
        txtOutputDir.setText(strOutputPath);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }        

        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {

            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(true);
                } else if ("done".equals(propertyName)) {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                    progressBar.setVisible(false);
                    progressBar.setValue(0);
                } else if ("message".equals(propertyName)) {
                    String text = (String) (evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer) (evt.getNewValue());
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(value);
                }
            }
        });
    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = METSCreatorGUIApp.getApplication().getMainFrame();
            aboutBox = new METSCreatorGUIAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
            System.out.println("lol");
        }
        METSCreatorGUIApp.getApplication().show(aboutBox);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtOutputDir = new javax.swing.JTextField();
        btnMETSOutput = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        txtObjName = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        txtCreators = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtDescription = new javax.swing.JTextArea();
        jLabel7 = new javax.swing.JLabel();
        txtRelation = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();
        txtPdbID = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();

        mainPanel.setName("mainPanel"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(metscreatorgui.METSCreatorGUIApp.class).getContext().getResourceMap(METSCreatorGUIView.class);
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        txtOutputDir.setText(resourceMap.getString("txtOutputDir.text")); // NOI18N
        txtOutputDir.setName("txtOutputDir"); // NOI18N

        btnMETSOutput.setText(resourceMap.getString("btnMETSOutput.text")); // NOI18N
        btnMETSOutput.setName("btnMETSOutput"); // NOI18N
        btnMETSOutput.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                actionOutputBrowse(evt);
            }
        });

        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        txtObjName.setText(resourceMap.getString("txtObjName.text")); // NOI18N
        txtObjName.setName("txtObjName"); // NOI18N

        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N

        txtCreators.setText(resourceMap.getString("txtCreators.text")); // NOI18N
        txtCreators.setName("txtCreators"); // NOI18N

        jLabel5.setText(resourceMap.getString("jLabel5.text")); // NOI18N
        jLabel5.setName("jLabel5"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        txtDescription.setColumns(20);
        txtDescription.setLineWrap(true);
        txtDescription.setRows(5);
        txtDescription.setText(resourceMap.getString("txtDescription.text")); // NOI18N
        txtDescription.setWrapStyleWord(true);
        txtDescription.setName("txtDescription"); // NOI18N
        jScrollPane1.setViewportView(txtDescription);

        jLabel7.setText(resourceMap.getString("jLabel7.text")); // NOI18N
        jLabel7.setName("jLabel7"); // NOI18N

        txtRelation.setText(resourceMap.getString("txtRelation.text")); // NOI18N
        txtRelation.setName("txtRelation"); // NOI18N

        jButton2.setText(resourceMap.getString("jButton2.text")); // NOI18N
        jButton2.setName("jButton2"); // NOI18N
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                actionCreate(evt);
            }
        });

        txtPdbID.setText(resourceMap.getString("txtPdbID.text")); // NOI18N
        txtPdbID.setName("txtPdbID"); // NOI18N

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        org.jdesktop.layout.GroupLayout mainPanelLayout = new org.jdesktop.layout.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jLabel1)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, mainPanelLayout.createSequentialGroup()
                        .add(txtOutputDir, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 748, Short.MAX_VALUE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(btnMETSOutput))
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, mainPanelLayout.createSequentialGroup()
                        .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                            .add(mainPanelLayout.createSequentialGroup()
                                .add(jLabel3)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(txtPdbID)
                                .add(18, 18, 18)
                                .add(jLabel2))
                            .add(jLabel4))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                            .add(txtObjName, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 629, Short.MAX_VALUE)
                            .add(org.jdesktop.layout.GroupLayout.LEADING, txtCreators, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 629, Short.MAX_VALUE)))
                    .add(mainPanelLayout.createSequentialGroup()
                        .add(jLabel5)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 707, Short.MAX_VALUE))
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jButton2)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, mainPanelLayout.createSequentialGroup()
                        .add(jLabel7)
                        .add(30, 30, 30)
                        .add(txtRelation, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 706, Short.MAX_VALUE)))
                .addContainerGap())
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(mainPanelLayout.createSequentialGroup()
                .add(35, 35, 35)
                .add(jLabel1)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(btnMETSOutput)
                    .add(txtOutputDir, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(39, 39, 39)
                .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                        .add(jLabel3)
                        .add(txtPdbID, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                        .add(txtObjName, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(jLabel2)))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(jLabel4)
                    .add(txtCreators, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(mainPanelLayout.createSequentialGroup()
                        .add(jLabel5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 203, Short.MAX_VALUE)
                        .add(123, 123, 123))
                    .add(mainPanelLayout.createSequentialGroup()
                        .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 308, Short.MAX_VALUE)
                        .add(18, 18, 18)))
                .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(txtRelation, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel7))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jButton2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 29, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        progressBar.setName("progressBar"); // NOI18N

        org.jdesktop.layout.GroupLayout statusPanelLayout = new org.jdesktop.layout.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(statusPanelSeparator, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 881, Short.MAX_VALUE)
            .add(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(statusMessageLabel)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 685, Short.MAX_VALUE)
                .add(progressBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(statusAnimationLabel)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(statusPanelLayout.createSequentialGroup()
                .add(statusPanelSeparator, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(statusMessageLabel)
                    .add(statusAnimationLabel)
                    .add(progressBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(3, 3, 3))
        );

        setComponent(mainPanel);
        setStatusBar(statusPanel);
    }// </editor-fold>//GEN-END:initComponents
    private void actionCreate(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_actionCreate

        if (validateCreate()) {
            jButton2.setEnabled(false);
            
            String fileName = "";
            
            if(txtPdbID.getText().trim().equals(""))
            {
                fileName = txtObjName.getText();
            }
            else
            {
                fileName = txtPdbID.getText().trim();
            }

            String path = MetsCreator.writeMETS(
                    txtOutputDir.getText() + File.separator + fileName + ".xml",
                    txtPdbID.getText() + " - " + txtObjName.getText(),
                    txtCreators.getText().split(","),
                    txtDescription.getText(), "dataset",
                    txtRelation.getText());
            
            JOptionPane.showMessageDialog(mainPanel, "Successfully Created Project Description\nWrote to: " + path,
				                       "Success", JOptionPane.INFORMATION_MESSAGE);
            
            jButton2.setEnabled(true);
        }
        
    }//GEN-LAST:event_actionCreate

    private boolean validateCreate() {

        try {
            if (!new File(txtOutputDir.getText()).exists()) {
                throw new Exception("Invalid output directory path");
            }
            else if(txtObjName.getText().equals(""))
            {
                throw new Exception("Please enter a project name");
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(mainPanel, e.getMessage(),
                    "Error", JOptionPane.ERROR_MESSAGE);
            return false;
        }

        return true;

    }

    private void actionOutputBrowse(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_actionOutputBrowse
        if (evt.getSource() == btnMETSOutput) {
            fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            int returnVal = fc.showOpenDialog(mainPanel);

            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                txtOutputDir.setText(file.getAbsolutePath());
            //This is where a real application would open the file.
            //log.append("Opening: " + file.getName() + "." + newline);
            } else {
            // log.append("Open command cancelled by user." + newline);
            }
        }
    }//GEN-LAST:event_actionOutputBrowse

    /*private boolean validateValidate() {
        // awesome function name alert
        
        try {
            if (!new File(txtOutputFile.getText()).exists()) {
                throw new Exception("Invalid METS file path");
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(mainPanel, e.getMessage(),
                    "Error", JOptionPane.ERROR_MESSAGE);
            return false;
        }

        return true;

    }  */  
    
   public static JOptionPane getNarrowOptionPane(
                       int maxCharactersPerLineCount) {
     // Our inner class definition
     class NarrowOptionPane extends JOptionPane {
       int maxCharactersPerLineCount;
       NarrowOptionPane(int maxCharactersPerLineCount) {
         this.maxCharactersPerLineCount = 
           maxCharactersPerLineCount;
       }
       public int getMaxCharactersPerLineCount() {
         return maxCharactersPerLineCount;
       }
     }


     return new NarrowOptionPane(
       maxCharactersPerLineCount);
   }



    class ErrorChecker extends DefaultHandler {

       public void error(SAXParseException e) throws SAXException {
       XSDPassed = false;
       JOptionPane pane = getNarrowOptionPane(50);
       pane.setMessage("Line " + e.getLineNumber() + "...\n" + e.getMessage());
       pane.setMessageType(JOptionPane.INFORMATION_MESSAGE);
       JDialog dialog = pane.createDialog(
         mainPanel, "Validation Failed");
       dialog.setVisible(true);
       }
    }    
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnMETSOutput;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    private javax.swing.JTextField txtCreators;
    private javax.swing.JTextArea txtDescription;
    private javax.swing.JTextField txtObjName;
    private javax.swing.JTextField txtOutputDir;
    private javax.swing.JTextField txtPdbID;
    private javax.swing.JTextField txtRelation;
    // End of variables declaration//GEN-END:variables
    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;
    final JFileChooser fc = new JFileChooser();
    final JFileChooser fco = new JFileChooser();
    private JDialog aboutBox;
    private boolean XSDPassed;
}
